package com.lagou.boot;


import com.lagou.handler.UserServerHandler;
import com.lagou.pojo.RpcRequest;
import com.lagou.serializer.JSONSerializer;
import com.lagou.serializer.RpcDecoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

/**
 * 自定义服务端启动初始化
 */
@Component
public class ServerBootStrap implements CommandLineRunner {

    @Autowired
    private UserServerHandler userServerHandler;

    @Override
    public void run(String... args) throws Exception {
        String host = "127.0.0.1";
        int port = 8888;
        startServer(host, port);
    }

    /**
     * hostName:ip地址 port:端口号
     * @param hostName
     * @param port
     */
    public void startServer(String hostName, int port) throws InterruptedException {
        NioEventLoopGroup boosGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();

        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(boosGroup, workGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline.addLast(new RpcDecoder(RpcRequest.class, new JSONSerializer()));
                        pipeline.addLast(new StringEncoder());
                        pipeline.addLast(userServerHandler);
                    }
                });
        serverBootstrap.bind(hostName, port).sync();
        System.out.println("Server Start on " + hostName + ", port: " + port);
    }

}
